<template>
  <div class="outter">
    <p v-if="!loaded" class="loading">正在加载pdf文件...</p>
    <div v-if="loaded" class="box">
      <div class="box-inner">
        <iframe id="pdfHtml" ref="iframeBodyFile" width="100%" height="100%" frameborder="0" :src="bodyFileUrl" />
      </div>
    </div>

    <div class="bottom-bar">
      <div v-if="sign" class="btn-g">
        <el-button class="add-btn" type="primary" :disabled="!canAdd" @click="openSign">添加签名</el-button>
        <el-button class="save-btn" type="primary" :disabled="!canSave" @click="pdfSign">保存签名</el-button>
      </div>
      <AddSign v-if="sign&&dVisible" :d-visible="dVisible" @addSucc="signAddSucc" @canAddFun="canAddFun" />

      <div v-if="seal" class="btn-g">
        <el-button class="add-btn" type="primary" :disabled="!canAdd" @click="openSign">选择印章</el-button>
        <el-button class="save-btn" type="primary" :disabled="!canSave" @click="pdfStamp">保存印章</el-button>
      </div>
      <ListSeals v-if="seal&&dVisible" :inputpwd="inputpwd" :d-visible="dVisible" @addSucc="selsAddSucc" @canAddFun="canAddFun" />

    </div>

    <DoingDialog />
  </div>
</template>

<script>

// import SignImgBox from './SignImgBox'
import AddSign from './AddSign'
import ListSeals from './ListSeals'
import $ from 'jquery'
if (!window.jQuery) {
    window.jQuery = $
}

export default {
    name: 'PdfTools',
    components: {
        AddSign, ListSeals
    },
    props: {
        inputpwd: { type: Boolean, default: true } // 是否需要用户输入密码
    },
    data() {
        return {
            sign: false, // 是否可签名
            seal: false, // 是否可盖章
            loaded: false,
            pdfId: '',
            canAdd: true,
            canSave: false,
            dVisible: false,
            signObj: {},
            signBoxShow: false, // 签名模块是否显示
            wfAttachUrl: 'workflow/wfBusiAttach',
            bodyfileName: '',
            bodyFileUrl: '',
            iframeBodyFile: null,
            fileType: 'BODY'
        }
    },
    computed: {

    },
    watch: {

    },
    created() {

    },
    beforeDestroy() {
        window.removeEventListener('message', this.iframeBtnClick, false)
    },
    mounted() {
        let fileurl = location.href
        fileurl = this.$route.query.fileurl
        if (fileurl !== undefined) {
            const urlQuery = fileurl.split('?')[1].split('&')
            const obj = {}
            urlQuery.forEach(data => {
                obj[data.split('=')[0]] = data.split('=')[1]
            })
            if (obj.filename) {
                this.bodyfileName = obj.filename
                document.title = this.bodyfileName
            }

            if (obj.attachType) {
                this.fileType = obj.attachType
            }

            fileurl = fileurl.split('&filename=')[0]

            // 签名
            if (this.$route.query.sign !== undefined) {
                this.sign = true
            }
            // 盖章
            if (this.$route.query.seal !== undefined) {
                this.seal = true
            }
        }
        this.wfAttachUrl = fileurl.split('/downloadById')[0].replace(process.env.VUE_APP_BASE_API + '/', '')

        this.pdfId = fileurl.split('attachIds=')[1].split('&')[0]

        this.bodyFileUrl = './plugins/PDFjs/web/viewer.html?file=' + encodeURIComponent(fileurl + '&widthType=100')
        this.loaded = true
        this.$nextTick(() => {
            this.iframeBodyFile = this.$refs.iframeBodyFile.contentWindow
        })

        window.addEventListener('message', this.iframeBtnClick, false)
    },
    methods: {
        // 打开签名二维码页
        openSign() {
            this.dVisible = true
            this.canAdd = false
        },

        // 获取盖章
        selsAddSucc(signObj) {
            this.signObj = signObj
            this.dVisible = false
            this.signBoxShow = true
            this.canSave = false
            this.canAdd = false
            this.iframeBodyFile.addImage('data:image/' + signObj.previewType + ';base64,' + signObj.imgFileData, signObj.width + 'px', signObj.height + 'px', 'seals')
        },
        // 获取签名
        signAddSucc(signObj) {
            this.signObj = signObj
            this.dVisible = false
            this.canAdd = false
            this.canSave = false
            this.iframeBodyFile.addImage('data:image/pngs;base64,' + signObj.imgFileData, '30%', 'auto', 'sign')
        },
        // 签名盖章，点击关闭
        canAddFun() {
            this.canAdd = true
            this.canSave = false
            this.dVisible = false
        },
        // 盖章签名锁定删除操作
        iframeBtnClick(data) {
            if (data.data === 'lock') {
                this.canAdd = false
                this.canSave = true
            } else if (data.data === 'unlock') {
                this.canAdd = false
                this.canSave = false
            } else if (data.data === 'delete') {
                this.canAdd = true
                this.canSave = false
            }
        },
        // 获取签名信息
        signInfo(scale, page, xPos, yPos) {
            this.signScale = scale
            this.signPage = page
            this.xPos = xPos
            this.yPos = yPos
            // 保存按钮可用
            this.canSave = true
        },
        // 保存签名
        pdfSign() {
            const dist = this.iframeBodyFile.getImgDis()
            const params = {
                attachId: this.pdfId,
                pageNum: dist.nowPage,
                percentage: dist.fullSize,
                xPos: dist.imgleft,
                yPos: dist.imgTop
            }

            this.$http({
                method: 'POST',
                url: this.wfAttachUrl + '/pdfSignature',
                contentType: 'application/x-www-form-urlencoded',
                params: params,
                data: { image: this.signObj.imgFileData }
            }).then(response => {
                if (response.code === 'success') {
                    this.$message.success('保存成功')
                    const bodyfilebox = window.opener.document.querySelector('#bodyfilebox')
                    if (bodyfilebox !== null) {
                        window.opener.location.reload()
                    }

                    setTimeout(() => {
                        window.close()
                    }, 700)
                } else {
                    this.$message.error(response.message)
                }
            })
        },
        // 保存电子印章
        pdfStamp() {
            const dist = this.iframeBodyFile.getImgDis()
            const params = {
                attachId: this.pdfId,
                pageNum: dist.nowPage,
                xPos: dist.imgleft,
                yPos: dist.imgTop,
                sealId: this.signObj.sealId,
                sealSessionId: this.signObj.sealSessionId,
                sealPassword: this.signObj.sealPassword,
                bodyfileName: this.bodyfileName,
                bodyfileType: this.fileType
            }
            this.$bus.emit('showDoingDialog', '正在保存印章，请稍候...')
            this.$http({
                method: 'POST',
                url: 'stamp/sealToFile',
                contentType: 'application/x-www-form-urlencoded',
                params: params
            }).then(response => {
                this.$bus.emit('closeDoingDialog')
                if (response.code === 'success') {
                    this.$message.success('盖章成功')
                    if (this.bodyfileName.indexOf('SignedFile_') === 0) {
                        window.opener.document.querySelector('#btnSaveSignedfile').click()
                    }
                    setTimeout(() => {
                        window.close()
                    }, 700)
                } else {
                    this.$message.error(response.message)
                }
            })
        }
    }
}
</script>

<style>
.bottom-bar .el-pager{position:relative;}
.bottom-bar .cover-li{position: absolute;top:0;left:0;right:0;bottom: 0;z-index: 2;background-color: transparent!important;cursor:default;}
</style>

<style scoped lang="scss">
.outter{
    position:relative;
    background: #666666;
    height: 100vh;
    overflow: hidden;
    .loading{padding-top:100px;text-align:center;color:#fff;margin-top:0;}
    .box{
        height:100%;
        .box-inner{position:relative;width:100%;height: 100%;}
    }
}
// .page{position: absolute;width:45px;height: 150px;top:50%;margin-top:-75px;opacity:0.8;z-index:99;font-size:30px;text-align:center;padding:0;}
// .page.prev{left:0;}
// .page.next{right:17px;margin-left:0;}
#the-canvas{width:100%;}

.bottom-bar{position: absolute;bottom:40px;text-align:center;width:100%;padding-right:17px;}
.bottom-bar .el-pagination{margin-bottom: 15px;}
</style>
